﻿using Share;
using UnityEngine;
public class PsActionDestruct : MonoBehaviour
{
    [Tooltip("销毁延迟时间，0表示立即销毁")]
    public float delayTime = 1.0f;

    [Tooltip("是否完全销毁对象，否则只是禁用")]
    public bool destroyCompletely = true;

    private SmartTimer m_stDelayTimer = new SmartTimer();
    public void DoSetDelayTime(float fDelayTime)
    {
        enabled = false;
        delayTime = fDelayTime;
        enabled = true;
    }
    private void OnEnable()
    {
        if (delayTime < 0)
        {
            Debug.LogWarning($"Invalid lifeTime value: {delayTime}, reset to 0");
            delayTime = 0;
        }

        if (delayTime == 0)
        {
            TriggerAction();
        }
        else
        {
            m_stDelayTimer.DoReset(delayTime);
        }
    }

    private void OnDisable()
    {
        m_stDelayTimer.DoClose();
    }

    public bool TriggerAction()
    {
        // 如果是池子里的对象，就按照对象池处理，通过池子创建的节点，会自动加这个节点
        if (GetComponent<ObjectPoolItem>() != null)
        {
            gameObject.SetActive(false);
            return true;
        }
        if (destroyCompletely)
        {
            gameObject.Destroy();
        }
        else
        {
            gameObject.SetActive(false);
        }
        return true;
    }

    private void Update()
    {
        if (m_stDelayTimer.DoUpdate())
        {
            TriggerAction();
        }
    }
}
